package com.example.hutoolpractic;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
@RequestMapping("/captcha")
@RestController
public class GetPricute {
    @Autowired
    private SetCaptcha setCaptcha;
    @RequestMapping("/get")
   public void get(HttpSession session,HttpServletResponse response){
       //定义图形验证码的长和宽
        ICaptcha captcha  = CaptchaUtil.createLineCaptcha(setCaptcha.getWidth(), setCaptcha.getHeight());      //图形验证码写出，可以写出到文件，也可以写出到流

        try {
            System.out.println(captcha.getCode());
            //输出到页面
            captcha.write(response.getOutputStream());
            //存储在session中
            session.setAttribute("key",captcha.getCode());
            response.setContentType("image/jpeg");

            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //Servlet的OutputStream记得自行关闭哦！



   }
@RequestMapping("/check")
   public boolean check(String captcha,HttpSession session){
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        String s = (String) session.getAttribute("key");
        if(captcha.equalsIgnoreCase(s)){
            return true;
        }else {
            return false;
        }


   }
}
